package com.jubotech.business.web.controller.user;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jubotech.business.web.domain.WxAccountInfo;
import com.jubotech.business.web.query.DeviceQuery;
import com.jubotech.business.web.service.WxAccountService;
import com.jubotech.framework.common.BaseController;
import com.jubotech.framework.common.DispatchMode;
import com.jubotech.framework.common.GridPage;
import com.jubotech.framework.common.ResultInfo;
import com.jubotech.framework.util.MD5Util;
import com.jubotech.framework.util.SessionUtil;

@Controller
@RequestMapping("/user")
public class DeviceController extends BaseController<WxAccountInfo> {

	@Autowired
	private WxAccountService service;
	 
	@RequestMapping("/device/{mode}/dispatch")
	public ModelAndView dispatch(HttpServletRequest request, @PathVariable String mode, Integer id) {
		Map<String, Object> model = new HashMap<>();
		model.put("mode", mode);
		if (DispatchMode.LIST_MODE.equals(mode)) {
			return new ModelAndView("/user/device/list", model);
		}
		if (DispatchMode.ADD_MODE.equals(mode)) {
			SessionUtil.setToken(request, MD5Util.makeToken());
			return new ModelAndView("/user/device/edit", model);
		}
		if (DispatchMode.UPDATE_MODE.equals(mode)) {
			SessionUtil.setToken(request, MD5Util.makeToken());
			model.put("info", service.getWeChatAccountByid(id));
			return new ModelAndView("/user/device/edit", model);
		}
		return new ModelAndView("/common/error");
	}

	@PostMapping("/device/pageList")
	@ResponseBody
	public ResultInfo pageList(HttpServletRequest request, DeviceQuery query) {
		query.setCid(SessionUtil.getUserCid(request));
		GridPage<WxAccountInfo> gridPage = new GridPage<>(service.pageList(query));
		return ResultInfo.success(gridPage);
	}

	@PostMapping("/device/add")
	@ResponseBody
	public ResultInfo add(HttpServletRequest request, WxAccountInfo info) {
		if (isRepeatSubmit(request)) {
			return ResultInfo.fail("请勿重复提交");
		}
		info.setCid(SessionUtil.getUserCid(request));
		return service.insert(info);
	}

	@PostMapping("/device/update")
	@ResponseBody
	public ResultInfo update(HttpServletRequest request, WxAccountInfo info) {
		if (isRepeatSubmit(request)) {
			return ResultInfo.fail("请勿重复提交");
		}
		info.setCid(SessionUtil.getUserCid(request));
		return service.updateDevice(info);
	}

	@PostMapping("/device/deletes")
	@ResponseBody
	public ResultInfo deletes(String ids) {
		service.deleteByIds(ids);
		return ResultInfo.success();
	}
	
}
